package cn.springsoter.core.s3.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

import cn.springsoter.core.oss.config.OssConfig;
import cn.springsoter.core.oss.props.OssProperties;
import cn.springsoter.core.oss.rule.IOssRule;
import cn.springsoter.core.s3.template.S3Template;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;

/**
 * S3配置类
 *
 * @author Kevin
 */
@Configuration
@AllArgsConstructor
@AutoConfigureAfter(OssConfig.class)
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(value = "springsoter.oss.enable", havingValue = "true")
public class S3Config {

	private OssProperties ossProperties;

	@Bean
	@SneakyThrows
	@ConditionalOnMissingBean(AmazonS3.class)
	public AmazonS3 amazonS3() {
		String region = StringUtils.defaultString(ossProperties.getRegion(), Regions.DEFAULT_REGION.getName());
		// 创建Amazon S3对象使用明确凭证
		BasicAWSCredentials credentials = new BasicAWSCredentials(ossProperties.getAccessKey(), ossProperties.getSecretKey());
		ClientConfiguration clientConfig = new ClientConfiguration();
		clientConfig.setSignerOverride("S3SignerType");// 凭证验证方式
		clientConfig.setProtocol(Protocol.HTTP);// 访问协议
		AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard()
				.withCredentials(new AWSStaticCredentialsProvider(credentials))
				.withClientConfiguration(clientConfig)
				.withEndpointConfiguration(
						/**
						 * 设置要用于请求的端点配置（服务端点和签名区域） url s3服务器地址 zone 存储的区域
						 */
						new AwsClientBuilder.EndpointConfiguration(ossProperties.getEndpoint(), region))
				.withPathStyleAccessEnabled(true)// 是否使用路径方式，是的话s3.xxx.sn/bucketname
				.build();
		return amazonS3;
	}

	@Bean
	@ConditionalOnBean({AmazonS3.class, IOssRule.class})
	@ConditionalOnMissingBean(S3Template.class)
	public S3Template s3Template(AmazonS3 s3, IOssRule ossRule) {
		return new S3Template(s3, ossRule, ossProperties);
	}

}
